using System;
using System.Collections;
using System.Globalization;
using System.Text.RegularExpressions;
using UnityEngine;

namespace I2.Loc
{
	public static class GoogleTranslation
	{
		public static void Translate(string text, string LanguageCodeFrom, string LanguageCodeTo, Action<string> OnTranslationReady)
		{
			WWW translationWWW = GetTranslationWWW(text, LanguageCodeFrom, LanguageCodeTo);
			CoroutineManager.pInstance.StartCoroutine(WaitForTranslation(translationWWW, OnTranslationReady, text.ToUpper() == text));
		}

		private static IEnumerator WaitForTranslation(WWW www, Action<string> OnTranslationReady, bool MakeAllCaps)
		{
			yield return www;
			if (!string.IsNullOrEmpty(www.error))
			{
				BCWDebug.LogError(www.error);
				OnTranslationReady(string.Empty);
			}
			else
			{
				string Translation = ParseTranslationResult(www.text, MakeAllCaps);
				OnTranslationReady(Translation);
			}
		}

		public static string ForceTranslate(string text, string LanguageCodeFrom, string LanguageCodeTo)
		{
			WWW translationWWW = GetTranslationWWW(text, LanguageCodeFrom, LanguageCodeTo);
			while (!translationWWW.isDone)
			{
			}
			if (!string.IsNullOrEmpty(translationWWW.error))
			{
				BCWDebug.LogError(translationWWW.error);
				return string.Empty;
			}
			return ParseTranslationResult(translationWWW.text, text.ToUpper() == text);
		}

		private static WWW GetTranslationWWW(string text, string LanguageCodeFrom, string LanguageCodeTo)
		{
			LanguageCodeFrom = GoogleLanguages.GetGoogleLanguageCode(LanguageCodeFrom);
			LanguageCodeTo = GoogleLanguages.GetGoogleLanguageCode(LanguageCodeTo);
			string url = string.Format("http://www.google.com/translate_t?hl=en&vi=c&ie=UTF8&oe=UTF8&submit=Translate&langpair={0}|{1}&text={2}", LanguageCodeFrom, LanguageCodeTo, Uri.EscapeUriString(text));
			return new WWW(url);
		}

		private static string ParseTranslationResult(string html, bool MakeAllCaps)
		{
			try
			{
				int num = html.IndexOf("TRANSLATED_TEXT") + "TRANSLATED_TEXT='".Length;
				int num2 = html.IndexOf("';INPUT_TOOL_PATH", num);
				string input = html.Substring(num, num2 - num);
				input = Regex.Replace(input, "\\\\x([a-fA-F0-9]{2})", (Match match) => char.ConvertFromUtf32(int.Parse(match.Groups[1].Value, NumberStyles.HexNumber)));
				input = Regex.Replace(input, "&#(\\d+);", (Match match) => char.ConvertFromUtf32(int.Parse(match.Groups[1].Value)));
				input = input.Replace("<br>", "\n");
				if (MakeAllCaps)
				{
					input = input.ToUpper();
				}
				return input;
			}
			catch (Exception ex)
			{
				BCWDebug.LogError(ex.Message);
				return string.Empty;
			}
		}
	}
}
